abstract class IPublisher {
  void post<T>(T event);
}

typedef ISubscriber<T> = void Function(T event);

/// 实现  发布事件的时候   拿到注册事件的状态

abstract class IEventBus extends IPublisher {
  void register<T>(ISubscriber<T> subscriber);
  void unregister<T>(ISubscriber<T> subscriber);
}

Type typeOf<T>() => T;

class XEventBus implements IEventBus {
  Map<Type, List<Function>> map = {};

  @override
  void register<T>(ISubscriber<T> subscriber) {
    Type type = typeOf<T>();
    if (!map.containsKey(type)) {
      map[type] = [];
    }
    map[type]?.add(subscriber);
  }

  @override
  void unregister<T>(ISubscriber<T> subscriber) {
    Type type = typeOf<T>();
    if (map.containsKey(type)) {
      map[type]?.remove(subscriber);
    }
  }

  @override
  void post<T>(T event) {
    Type type = typeOf<T>();
    if (map.containsKey(type)) {
      var subscribers = map[type];
      subscribers?.forEach((subscriber) => subscriber.call(event));
    }
  }
}

class EventBusProvider {
  static final EventBusProvider _instance = EventBusProvider._internal();
  XEventBus _singleEventBus = XEventBus();

  factory EventBusProvider() {
    return _instance;
  }

  static XEventBus get singleEventBus => _instance._singleEventBus;

  EventBusProvider._internal();

  static XEventBus get newEventBus => XEventBus();
}
